package com.emm.yixun.website.controller.customer;

//框架包
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.common.model.Follow;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.FollowDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.customer.service.FollowServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
//common
//website
//变化的引用

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/customer/follow/")
public class FollowController extends BaseController<Follow> {

	@Autowired
	private FollowServiceFacade followServiceFacade;

	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	private final String resourcesName = "resName_customer_follow_list";

	// @RequestMapping(value="index")
	// public String index(ModelMap map){
	// if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
	// //查询菜单按钮权限
	// map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
	// return "/customer/follow/list";
	// }
	// return Const.NO_AUTHORIZED_URL;
	// }

	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request, ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:list")) {
			request.setAttribute("permitBtn", getPermissionBtnArray());
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			ProjectDto projectDto = new ProjectDto();
			projectDto.setDelFlag("0");
			projectDto.setPermissionUserId(user.getId());
			projectDto.setResourcesCode("menu_0003_0001");
			projectDto.setMerchantId(user.getMerchantId());
			List<Project> projects = projectServiceFacade.findByDto(projectDto).getEntity();
			com.alibaba.fastjson.JSONArray dtArray = new com.alibaba.fastjson.JSONArray();
			String projectId = "";
			if (null != projects) {
				for (Project project : projects) {
					JSONObject row = new JSONObject();
					row.put("id", project.getId());
					row.put("projectName", project.getProjectName());
					dtArray.add(row);
				}
				projectId = String.valueOf(projects.get(0).getId());
			}
			map.put("projects", dtArray.toJSONString());
			map.put("projectId", projectId);
			return new ModelAndView("/customer/follow/list");
		}
		return new ModelAndView(Const.NO_AUTHORIZED_URL);
	}

	/**
	 * ui优化版 功能描述: <br>
	 * 〈功能详细描述〉
	 * 
	 * @param menu
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "getIndex", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes getIndex(String menu) {
		AjaxRes ar = getAjaxRes();
		Map<String, Object> map = new HashMap<String, Object>();
		/*
		 * 1.判断权限2.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:list"))) {
			map.put("permitBtn", getPermissionBtnArray());
			String resourcesCode = ShiroUtil.getDataPermissionResources(resourcesName);
			if (StringUtils.isBlank(resourcesCode))
				resourcesCode = menu;
			ShiroUtil.setDataPermissionResources(resourcesName, resourcesCode);
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			FollowDto dto = new FollowDto();
			dto.setPermissionUserId(user.getId());
			dto.setMerchantId(user.getMerchantId());
			if (StringUtils.isNotBlank(resourcesCode)) {
				dto.setResourcesCode(resourcesCode);
			}
			dto.setOrders(" t.create_time desc ");
			List<Project> projects = followServiceFacade.findProjectByDto(dto).getEntity();
			com.alibaba.fastjson.JSONArray dtArray = new com.alibaba.fastjson.JSONArray();
			String projectId = "";
			if (null != projects) {
				for (Project project : projects) {
					JSONObject row = new JSONObject();
					row.put("id", project.getId());
					row.put("projectName", project.getProjectName());
					dtArray.add(row);
				}
				projectId = String.valueOf(projects.get(0).getId());
			}
			map.put("projects", dtArray);
			map.put("projectId", projectId);
			ar.setSucceed(map);
		} else {
			ar.setFailMsg(Const.NO_AUTHORIZED_URL);
		}
		return ar;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(FollowDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<FollowDto> response = followServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:view"))) {
			try {
				Response<Follow> response = followServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(FollowDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		try {
			Response<Integer> response = followServiceFacade.updateByPrimaryKey(dto, true);
			if (response.isSuccess()) {
				ar.setSucceedMsg(Const.UPDATE_SUCCEED);
			} else {
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.UPDATE_FAIL);
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:delete"))) {
			try {
				Response<Integer> response = followServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	@RequestMapping(value = "returnProjectName")
	@ResponseBody
	public List<Project> returnProjectName(HttpServletRequest request) {
		User user = ShiroUtil.getCurrentUser();
		// 入参
		String resName = request.getParameter("resourcesName");
		String resCode = request.getParameter("resourcesCode");
		String needAuth = request.getParameter("needAuth");
		if (null != resCode || !"".equals(resCode)) {
			user.setResourcesCode(resCode);
		}
		//当功能不需要权限过滤时，使用此参数进行避开
		if(StringUtils.isNotEmpty(needAuth) && "F".equals(needAuth)){
			user.setResourcesCode("");
		}
		// 项目数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(request.getParameter("resourcesName"));
		if (null == resCode || "".equals(resCode)) {
			user.setResourcesCode(resourcesCode);
		} else if ("".equals(resourcesCode)) {
			ShiroUtil.setDataPermissionResources(resName, resCode);
		}

		List<Project> projectList = projectServiceFacade.getProjectByUser(user);
		return projectList;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Page<FollowDto> list(FollowDto dto, Integer limit, Integer page) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:list")) {
			try {
				dto.setOrders(" t.follow_time desc ");
				if (dto.getFollowTimeAfter() != null && !dto.getFollowTimeAfter().equals("")) {
					dto.setFollowTimeAfter(dto.getFollowTimeAfter() + " 23:59:59");
				}
				if (dto.getNextFollowTimeAfter() != null && !dto.getNextFollowTimeAfter().equals("")) {
					dto.setNextFollowTimeAfter(dto.getNextFollowTimeAfter() + " 23:59:59");
				}
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				String resourcesCode = dto.getResourcesCode();
				if (StringUtils.isBlank(resourcesCode)){
					resourcesCode = ShiroUtil.getDataPermissionResources(resourcesName);
				}
				ShiroUtil.setDataPermissionResources(resourcesName, resourcesCode);
				dto.setResourcesCode(resourcesCode);
				dto.setPermissionUserId(user.getId());
				Response<Page<FollowDto>> depositListResDto = followServiceFacade.getFollowList(dto, limit, page);
				if (depositListResDto.isSuccess()) {
					Page<FollowDto> pages = depositListResDto.getEntity();
					pages.setPageNumber(page);
					return pages;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<FollowDto>();
	}

	// 分页查询
	@RequestMapping(value = "getlist", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes getlist(FollowDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:follow:list"))) {
			try {
				dto.setOrders(" t.follow_time desc ");
				if (dto.getFollowTimeAfter() != null && !dto.getFollowTimeAfter().equals("")) {
					dto.setFollowTimeAfter(dto.getFollowTimeAfter() + " 23:59:59");
				}
				if (dto.getNextFollowTimeAfter() != null && !dto.getNextFollowTimeAfter().equals("")) {
					dto.setNextFollowTimeAfter(dto.getNextFollowTimeAfter() + " 23:59:59");
				}
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				String resourcesCode = ShiroUtil.getDataPermissionResources(resourcesName);
				if (StringUtils.isNotBlank(resourcesCode))
					dto.setResourcesCode(resourcesCode);
				dto.setPermissionUserId(user.getId());
				Response<Page<FollowDto>> depositListResDto = followServiceFacade.getFollowList(dto, pageSize, pageNum);
				if (depositListResDto.isSuccess()) {
					Page<FollowDto> pages = depositListResDto.getEntity();
					pages.setPageNumber(pageNum);
					ar.setSucceed(pages);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}
}
